"""
本文件用于处理mongo的相关操作

"""
import traceback
from pymongo import MongoClient  
from urllib.parse import quote_plus

from pymongo.errors import ConnectionFailure
            

class Mongo_handler:
    def __init__(self,config) -> None:
        if config.get("password"):
            uri = "mongodb://%s:%s@%s:%s" % (
                    quote_plus(config["user"]), quote_plus(config["password"]), config["host"],config["port"])
            print(uri)
            self.client = MongoClient(uri)  

        else:
            
            self.client = MongoClient("mongodb://localhost:27017/")

        # try:
        #         # The ping command is cheap and does not require auth.
        #     self.client.admin.command('ping')

        # except ConnectionFailure:
        #     print("Server not available")


        database_name = config["database"]


        self.db = self.client[database_name]  
  
        

    
    def insert(self,document):
        """
        插入数据
        """
        try:
            # 使用数据的 group 作为 collection 
            collection_name = document["group_name"]
            self.collection = self.db[collection_name]
            self.collection.insert_one(document)  
            return True
        except :
            print(traceback.format_exc())
